package com.cwg.dict.ui.cli.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.commons.lang.CharUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.edu.ynu.sei.dict.service.core.IDictQueryService;

import com.cwg.dict.service.DictManager;
import com.cwg.dict.service.Historical;
import com.cwg.dict.service.Speaker;
import com.cwg.dict.service.impl.HistoricalImpl;
import com.cwg.dict.ui.cli.CommandLineInput;

public class CommandLineInputImpl implements CommandLineInput {

	private DictManager		dictManager;
	private Historical		historical;
	private String			input;
	private Logger			logger	= LoggerFactory.getLogger(CommandLineInputImpl.class);
	private Speaker			speaker;
	private StemDictLayout	stemDictLayout;

	public DictManager getDictManager() {
		return dictManager;
	}

	public Historical getHistorical() {
		return historical;
	}

	public String getInput() {
		return input;
	}

	@Override
	public String[] getOutput() {
		List<String> results = new ArrayList<String>();
		stemDictLayout.input(input);
		if (CharUtils.isAscii(input.charAt(0))) {
			try {
				collectionOutputData(stemDictLayout, results);
			} catch (Exception e) {
				logger.warn("can't not found word [" + input + "] in stem dictionary", e);
			}
		}

		IDictQueryService[] services = dictManager.allDictServices();
		logger.info("service count of DictManager {}", services.length);
		for (IDictQueryService service : services) {
			DictLayout dictLayout = new DictLayout();
			dictLayout.input(input);
			dictLayout.setDicService(service);
			try {
				collectionOutputData(dictLayout, results);
			} catch (Exception e) {
				// ignore exception when word not found in dictionary 
			}
		}
		results.add("**********************************\n\n\n");
		return results.toArray(new String[results.size()]);
	}

	public Speaker getSpeaker() {
		return speaker;
	}

	public StemDictLayout getStemDictLayout() {
		return stemDictLayout;
	}

	@Override
	public void input(String input) {
		this.input = input;
		((HistoricalImpl) historical).add(input);
	}

	public void setDictManager(DictManager dictManager) {
		this.dictManager = dictManager;
	}

	public void setHistorical(Historical historical) {
		this.historical = historical;
	}

	public void setSpeaker(Speaker speaker) {
		this.speaker = speaker;
	}

	public void setStemDictLayout(StemDictLayout stemLayout) {
		this.stemDictLayout = stemLayout;
	}

	private void collectionOutputData(AbstractDictLayout layout, List<String> results) {
		String[] header = layout.getHeader();
		String[] separator = layout.getSeparator();
		String[] content = layout.getContent();
		logger.debug("add header of [{}] to results", header);
		results.addAll(Arrays.asList(header));
		results.addAll(Arrays.asList(content));
		results.addAll(Arrays.asList(separator));
	}
}
